from ninja import Router, Schema

router = Router()

from datetime import date

class EmployeeIn(Schema):
    first_name: str
    last_name: str
    department_id: int = None
    birthdate: date = None

class EmployeeOut(Schema):
    id: int
    first_name: str
    last_name: str
    department_id: int = None
    birthdate: date = None

from .models import Employee,Department
@router.post('/add')
def lst_add(request,payload: EmployeeIn):
    print(payload,type(payload))
    employee = Employee.objects.create(**payload.dict())
    print(employee.__dict__)
    return {'id': employee.id} # 框架自动将字典转JSON响应

from django.shortcuts import get_object_or_404
@router.get('/get/{employee_id}', response=EmployeeOut)
def info_get(request,employee_id:int):
    employee = get_object_or_404(Employee,id=employee_id)
    return employee # 直接返回ORM对象。repsonse schema 自动进行数据库反回的数据检验，并转换JSON

from typing import List
@router.get('/list',response=List[EmployeeOut])
def lst(request,page:int=1, size:int=10):
    queryset = Employee.objects.all()
    # page =1
    # [0:9]

    # page=2
    # [10:19]
    qs = queryset[page-1:page*size] # 直接返回queryset
    print(qs)
    return qs

@router.patch('/patch/{employee_id}')
def info_put(request,employee_id:int,payload:EmployeeIn):
    employee = get_object_or_404(Employee,id=employee_id)
    print(employee)
    for attr, value in payload.dict().items():
        setattr(employee,attr,value)
    # 等价
    # employee.first_name = payload.first_name
    # employee.last_name = payload.last_name
    # employee.department_id = payload.department_id
    # employee.birthdate = payload.birthdate

    employee.save()
    return {'success': True}



@router.delete('/delete/{employee_id}')
def info_delete(request,employee_id:int):
    employee = get_object_or_404(Employee, id=employee_id)
    employee.delete()
    return {'success':True}
